﻿//就绪函数
$(function () {
    Show()
})
//库位显示
function Show() {
    layui.use(function () {
        var table = layui.table;
        var laydate = layui.laydate;
        laydate.render({
            elem: '#ID-laydate-demo',
            done: function (value, date) {
                // 将选择的日期字符串转换为Date对象
                var selectedDate = new Date(value);
                // 减去8个小时，8小时换算成毫秒为8 * 60 * 60 * 1000
                selectedDate.setTime(selectedDate.getTime() - 8 * 60 * 60 * 1000);
                // 再将调整后的Date对象转换回期望的日期字符串格式（这里简单示例格式，可按需调整）
                var adjustedDateStr = selectedDate.toISOString().slice(0, 19).replace('T', ' ');
                console.log(adjustedDateStr);
                sessionStorage.setItem("adjustedDateStr", adjustedDateStr)
                setTimeout(function () {
                    sessionStorage.setItem("adjustedDateStr"," ")
                }, 4000);
                // 这里可以根据业务需求，将调整后的日期字符串赋值到相应位置等操作
            }
        });

        var procuredNumber = $("#procuredNumber").val()
        var AddTime = sessionStorage.getItem("adjustedDateStr")
        var procuredState = $("#procuredState").val()
        //console.log(AddTime)
        // 先进行表格的初始渲染
        table.render({
            elem: '#carriertable',  // 表格元素的选择器
            page: {
                limit: 5,
                limits: [5, 8, 10]
            },
            toolbar: '#toolbarDemo',//导出
            defaultTolbar: ['exports'],//导出
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'procuredNumber', title: '采购编号' },
                { field: 'feedstockNumber', title: '采购原料编号' },
                { field: 'feedstockName', title: '采购原料名称' },
                { field: 'feedstockNum', title: '采购原料数量' },
                {
                    field: 'addTime', title: '申请日期', templet: function (x) {
                        return formatTime(x.addTime)
                    }
                },
                {
                    field: 'procuredState', title: '状态', templet: function (x) {
                        if (x.procuredState == 0) {
                            return "待采购"
                        } else {
                            return "已采购"
                        }
                    }
                }, 
                {
                    field: '', title: '操作', width: 400 , templet: function (d) {
                        return '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" onclick="Supplier(' + d.procuredId + ')">选择供应商</button>' +
                            '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.procuredId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                            '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" onclick="particulars(' + d.procuredId + ')">查看</button>'+
                            '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.procuredId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                    }
                }
            ]],
            // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
            data: []
        });
        var data = {
            pageIndex: 1,
            pageSize: 80,
            procuredNumber: procuredNumber,
            AddTime: AddTime,
            procuredState: procuredState
        }
        $.ajax({

            url: "/RawMaterial/ProcuredShowsj",
            type: "get",
            data: data,
            success: function (data) {
                data = JSON.parse(data);
                console.log(data.data.plist);
                console.log(data.data)
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('carriertable', {
                    page: {
                        limit: 5,
                        limits: [5, 8, 10]
                    },
                    data: data.data.plist
                });
            },
            error: function () {
                console.log("请求失败");
            }
        });
    })
    // 定义时间格式转换函数
    function formatTime(timeStamp) {
        if (timeStamp) {
            var date = new Date(timeStamp);
            var year = date.getFullYear();
            var month = ('0' + (date.getMonth() + 1)).slice(-2);
            var day = ('0' + date.getDate()).slice(-2);
            var hour = ('0' + date.getHours()).slice(-2);
            var minute = ('0' + date.getMinutes()).slice(-2);
            var second = ('0' + date.getSeconds()).slice(-2);
            return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        }
        return "";
    }
}
//编辑
window.editData = function (id) {
    localStorage['procuredId'] = id;
    location.href = '/RawMaterial/ProcuredUpdate';
}

//选择供应商
function Supplier(procuredId) {
    localStorage['procuredId'] = procuredId
    location.href = "/Rawmaterialtesting/RawmaterialtestingAddView";
    //添加物流信息
    //toLogisticsAdd(procuredId)
}

//添加物流信息
function toLogisticsAdd(procuredId) {
    var lisy = {
        orderID: 0,
        purchaseNumber: ""
    }
    $.ajax({
        url: "/RawMaterial/ProcuredMondel",
        type: "get",
        data: {
            Id: procuredId,
        },
        success: function (data) {
            data = JSON.parse(data);
            console.log(data.data);
            // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
            $(data.data).each(function () {
                lisy.purchaseNumber = this.procuredNumber
                console.log(lisy)
                $.ajax({
                    url: '/Supplier/LedgerInfoLogisticsAdd',
                    type: 'post',
                    data: { data: JSON.stringify(lisy), token: localStorage.getItem("token") },
                    success: function (res) {
                        var s = JSON.parse(res)
                        console.log(res)
                        if (s.code == 1) {
                            layer.alert("添加成功");
                        }
                        else {
                            layer.alert("添加失败");
                        }
                    }
                })
            })
        }
    });
}
//查看
function particulars(procuredId) {
    localStorage["procuredparticularsID"] = procuredId
    $.ajax({
        url: "/RawMaterial/ProcuredMondel",
        type: "get",
        data: {
            Id: procuredId,
        },
        success: function (data) {
            data = JSON.parse(data);
            console.log(data.data.procuredState);
            if (data.data.procuredState=="1") {
                location.href = "/RawMaterial/ProcuredParticulars2";
            } else {
                location.href = "/RawMaterial/ProcuredParticulars";
            }
        }
    });
}

//删除采购原料
window.deleteData = function (id) {
    layer.confirm('确定删除该条数据吗？', function (index) {
        $.ajax({
            url: '/RawMaterial/ProcuredDelete',
            type: 'post',
            data: { data: JSON.stringify(id), token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code == 1) {
                    layer.alert("删除成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");
                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    })
}